<template>
    <div class="form_modal">
        <el-dialog
            :visible.sync="modal1"
            :close-on-click-modal="false"
            center
            :before-close="handleClose">
        <div class="modal_title">
            <span>{{title_name}}</span>
        </div>
            <el-form :model="formData" :rules="rules" ref="formData" label-width="120px">
                <el-row :gutter="24">
                    <el-col :span="11">
                        <el-form-item label="用户名称" prop="userName">
                            <el-input v-model="formData.userName" placeholder="请输入客户名称" :disabled="title_name === '编辑用户'"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="formData.password" placeholder="请输入密码" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="checkPass">
                            <el-input type="password" v-model="formData.checkPass" placeholder="请输入密码" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="常用邮箱" prop="userEmail">
                            <el-input v-model="formData.userEmail" placeholder="请输入邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="选择客服" prop="csId">
                            <el-select v-model="formData.csId" placeholder="请选择客服" @change="changecsId" style="width:100%">
                                <el-option v-for="(item, index) in csIdTypeArry" :value="item.id" :label="item.csName" :key="index">
                                    {{ item.csName}}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="用户账号" prop="account">
                            <el-input v-model="formData.account" :minlength="5" placeholder="请输入用户账号" :disabled="title_name === '编辑用户'"></el-input>
                        </el-form-item>
                        <el-form-item label="账号类型" prop="accountType">
                            <el-select v-model="formData.accountType" placeholder="请选择账号类型" @change="changeAccountType" style="width:100%">
                                <el-option v-for="(item, index) in accountTypeArry" :value="item.id" :label="item.tpyeName" :key="index">
                                    {{item.tpyeName}}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="手机号" prop="userPhone">
                            <el-input v-model="formData.userPhone" :maxlength="11" placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item label="用户状态" prop="status">
                            <el-select v-model="formData.status" placeholder="请选择用户状态" @change="changeStatus" style="width:100%">
                                <el-option v-for="(item, index) in userStatusArry" :value="item.status" :label="item.statusinfo" :key="index">
                                    {{item.statusinfo}}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="备注信息" prop="remark">
                            <el-input type="textarea" v-model="formData.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="省份" prop="province">
                            <el-select v-model="formData.province" filterable @change="selectProvinceFun($event)" placeholder="请选择省份" :disabled="title_name === '编辑用户'">
                                <el-option :value="item.id" :label="item.name" v-for="(item, index) in provinceList"  style="width: 100%;" :key="index"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="city" label-width="40px">
                            <el-select v-model="formData.city" filterable @change="selectCityFun($event)" placeholder="请选择城市" :disabled="title_name === '编辑用户'">
                                <el-option :value="item.id" :label="item.name" v-for="(item, index) in cityList" :key="index"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区县" prop="county" label-width="40px">
                            <el-select v-model="formData.county" filterable @change="countyFun($event)" placeholder="请选择区县" :disabled="title_name === '编辑用户'">
                                <el-option :value="item.id" :label="item.name" v-for="(item, index) in areaList" :key="index"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 保存--取消按钮 -->
            <el-row :gutter="24" type="flex" justify="end">
                <el-col :span="3">
                    <el-button type="primary" @click="submitForm('formData')">确 定</el-button>
                </el-col>
                <el-col :span="3">
                    <el-button @click="handleClose('formData')">取 消</el-button>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
import { searchAccountType, searchCsIdStatus, userStatusType, userInfoSave, userInfoEdmit} from '@/api/userApi'
import { searchCity } from '@/api/home'
export default {
    props:['historyData', 'title'],
    data(){
        //密码验证
        const validatePssWord = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码!'))
            } else if (!/^(\w){6,20}$/.test(value)) {
                callback(new Error('请输入6-20个字母/数字/下划线!'))
            } else {
                callback()
            }
        };
        // 密码再次验证
        const validateCheckPass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入确认密码!'))
            } else if (value !== this.formData.password) {
                callback(new Error('两次密码不一致!'))
            } else {
                callback()
            }
        };
        // 邮箱验证
        const validateEmail = (rule, value, callback) => {
             if (value === '') {
	          callback(new Error('请正确填写邮箱'));
	        } else {
	          if (value !== '') { 
	            var reg=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
	            if(!reg.test(value)){
	              callback(new Error('请输入有效的邮箱'));
	            }
	          }
	          callback();
	        }
        };
        //手机号验证
        const validatePhone = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('手机号不能为空！'))
            } else if (!/^1[34578]\d{9}$/.test(value)) {
                callback(new Error('请输入正确的手机号！'))
            } else {
                callback()
            }
        };
        // 用户名称验证
        const validateUserName = (rule, value, callback) => {
            if (value === '') {
                return callback(new Error('请输入用户名称！'))
            } else if (!/^[\u4e00-\u9fa5]+$/.test(value)) {
                return callback(new Error('请输入正确的中文用户名称!'))
            } else {
                return callback()
            }
        }
        //用户账号验证
        const validateAccount = (rule, value, callback) => {
            if (value === '') {
                return callback(new Error('请输入用户账号!'))
            } else if (!/^[a-zA-Z\d]+$/.test(value)) {
                return callback(new Error('请输入正确的用户账号!'))
            } else {
                return callback()
            }
        }
        return {
            title_name: '',
            modal1: false,
            //用户类型
            csIdTypeArry:[],
            //用户状态
            userStatusArry:[],
            //账号类型数组
            accountTypeArry:[],
            provinceList:[], //省
            cityList: [], //市
            areaList: [], //区
            formData: {
                userName: '',
                password: '',
                checkPass: '',
                userEmail: '',
                account: '',
                userPhone: '',
                status: '',
                statusInfo: '',
                remark: '', //备注
                csId: '',  // 客服状态
                province: '', //省
                provinceName: '',
                city: '', //市
                cityName: '',
                county: '', //区
                countyName: ''
            },
            rules: {
                userName: [
                    { required: true, message: '用户名称不能为空!', trigger: 'blur' },
                    { type: 'string', max: 50, message: '不能超过50个字符', trigger: 'blur' },
                    { validator: validateUserName, trigger: 'blur' }
                ],
                account: [
                    { required: true, validator: validateAccount, type: 'string', trigger: 'blur' }
                ],
                userPhone: [
                    { required: true, message: '手机号不能为空!', trigger: 'blur'},
                    { validator: validatePhone, trigger: 'blur'}
                ],
                password: [
                    { required: true, type: 'string', min: 6, validator: validatePssWord, trigger: 'blur' }
                ],
                checkPass: [
                    { required: true, type: 'string', min: 6, validator: validateCheckPass, trigger: 'blur' }
                ],
                userEmail:[
                    { message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', validator: validateEmail, message: '请输入邮箱地址', trigger: ['blur', 'change'] }
                ],
                status: [
                    { required: true, type: 'number', trigger: 'blur' }
                ],
                csId:[
                    { required: true, type: 'string', message: '客服状态不能为空!', trigger: 'blur' }
                ]
            },
        }
    },
    methods:{
        // 改变省
        selectProvinceFun(province){
            if (province){
                this.formData.province = province;
                // console.log("选择的省:", this.formData.province);
                
                let data2 = { parentId: this.formData.province };
                //回调接口
                searchCity(data2).then((res)=>{
                    if (res.statusCode == "200"){
                        this.cityList = [];
                        // console.log("查询所有的市级", res.data);
                        res.data.map(v=>{
                            this.cityList.push({name: v.name, id: v.id })
                        })
                    }
                })

            }
        },
        //改变市
        selectCityFun(city){
            if (city) {
                this.formData.city = city;
                // console.log("选择的市:", this.formData.city);

                let data3 = { parentId: this.formData.city };
                //回调接口
                searchCity(data3).then((res)=>{
                    if (res.statusCode == "200"){
                        this.areaList = [];
                        // console.log("查询所有的区/县:", res.data);
                        res.data.map(v=>{
                            this.areaList.push({name: v.name, id: v.id })
                        })
                    }
                })  
            }
        },
        // 改变区/县
        countyFun(area){
            if (area){
                this.formData.county = area;
            }
        },
        //改变账号类型
        changeAccountType(type){
            console.log("账号类型:", type)
             if (type){
                this.formData.accountType = type;
            }
        },
        //改变客服状态
        changecsId(val){
            console.log("客服状态:", val)
            if (val){
                this.formData.csId = val;
            }
        },
        //改变用户状态
        changeStatus(status){
            console.log("用户状态:", status)
            if (status){
                this.formData.status = status;
            }
        },

        //保存用户信息
        addForm() {
            this.$refs['formData'].validate((valid) => {
                if (valid) {
                    // 查出省的name
                    this.provinceList.map(v=>{
                        if (this.formData.province == v.id){
                            this.formData.provinceName = v.name
                        }
                    })

                    // 查出市的name
                    this.cityList.map(k=>{
                        if (this.formData.city == k.id){
                            this.formData.cityName = k.name
                        }
                    })

                    //查出区/县的name
                    this.areaList.map(m=>{
                        if (this.formData.county == m.id){
                            this.formData.countyName = m.name
                        }
                    })

                    // 查出用户状态 statusInfo 
                    this.userStatusArry.map(n=>{
                        if (this.formData.status == n.status){
                            this.formData.statusInfo = n.statusinfo
                        }
                    })

                    // 回调接口
                    userInfoSave(this.formData).then((res)=>{
                    //    console.log("save:", res.data); 
                        if ( res.statusCode == "200"){
                            this.$message({message: '保存成功！！！',type: 'success'});
                            this.$emit('submit', this.formData);// 子传给父， 查询所有
                            this.modal1 = false;

                            //清空上次记录
                            this.formData = {
                                userName: '',
                                password: '',
                                checkPass: '',
                                userEmail: '',
                                account: '',
                                userPhone: '',
                                status: '',
                                statusInfo: '',
                                remark: '', //备注
                                csId: '',  // 客服状态
                                province: '', //省
                                provinceName: '',
                                city: '', //市
                                cityName: '',
                                county: '', //区
                                countyName: ''
                            };
                        }
                    })
                } else {
                    this.$message({showClose: true, message: 'error submit!!', type: 'error'});
                    return false;
                }
            });
        },

        //修改用户信息
        edmitForm(){
            this.$refs['formData'].validate((valid) => {
                if (valid) {
                    // 查出省的name
                    this.provinceList.map(v=>{
                        if (this.formData.province == v.id){
                            this.formData.provinceName = v.name
                        }
                    })

                    // 查出市的name
                    this.cityList.map(k=>{
                        if (this.formData.city == k.id){
                            this.formData.cityName = k.name
                        }
                    })

                    //查出区/县的name
                    this.areaList.map(m=>{
                        if (this.formData.county == m.id){
                            this.formData.countyName = m.name
                        }
                    })

                    // 查出用户状态 statusInfo 
                    this.userStatusArry.map(n=>{
                        if (this.formData.status == n.status){
                            this.formData.statusInfo = n.statusinfo
                        }
                    })

                    // 回调接口
                    userInfoEdmit(this.formData).then((res)=>{
                    //    console.log("save:", res.data); 
                        if ( res.statusCode == "200"){
                            this.$message({message: '修改成功！！！', type: 'success'});
                            this.$emit('submit', this.formData);// 子传给父， 查询所有
                            this.modal1 = false;
                        }
                    })
                } else {
                    this.$message({showClose: true, message: 'error submit!!', type: 'error'});
                    return false;
                }
            });
        },

        // 用户(新增/编辑) 保存按钮
        submitForm() {
            if (this.title_name === '新增用户') {
                this.addForm(); //回调 新增接口
            } else if (this.title_name === '编辑用户') {
                this.edmitForm(); //回调 编辑接口
            }
        },

        // 弹层取消、关闭
        handleClose(){
            this.$refs['formData'].resetFields();
            this.modal1 = false;
        },

        //查询省-市-区/县
        searchCityData(){
            let data1 = {parentId: 0 };
            //回调接口
            searchCity(data1).then((res)=>{
                if (res.statusCode == "200"){
                    this.provinceList = [];
                    // console.log("查询所有省级的接口", res.data);
                    res.data.map(v=>{
                        this.provinceList.push({name: v.name, id: v.id })
                    })
                }
            })
        },

        //查询账号类型的接口
        search_accountType(){
          searchAccountType().then((res)=>{
            // console.log("账号类型:", res.data);
            if (res.statusCode == "200"){
                this.accountTypeArry = [];
                res.data.map(v=>{
                    this.accountTypeArry.push({ id: v.id, tpyeName: v.tpyeName })
                })
            }
          })  
        },

        //查询状态正常的客服
        searchCsIdStatusInfo(){
            let data3 = {
                status: 0
            };
            // 回调接口
            searchCsIdStatus(data3).then((res)=>{
                // console.log("查询状态正常的客服:", res.data)
                if (res.statusCode == "200"){
                    this.csIdTypeArry = [];
                    res.data.map(v=>{
                        this.csIdTypeArry.push({id: v.id,  csName: v.csName })
                    })
                }
            })
        },

        //查询用户类型接口
        search_userType(){
            userStatusType().then((res)=>{
                // console.log("用户类型:", res.data);
                if (res.statusCode == "200"){
                    this.userStatusArry = [];
                    res.data.map(v=>{
                        this.userStatusArry.push({status: v.status, statusinfo: v.statusinfo})
                    })
                }
            })  
        },

        // 判断tilte 是哪个model框
        get_title() {
            if (this.title === '新增用户') {
                this.formData = {
                    userName: '',
                    password: '',
                    checkPass: '',
                    userEmail: '',
                    account: '',
                    userPhone: '',
                    status: '',
                    statusInfo: '',
                    remark: '', //备注
                    csId: '',  // 客服状态
                    province: '', //省
                    provinceName: '',
                    city: '', //市
                    cityName: '',
                    county: '', //区
                    countyName: ''
                }
            } else {
                this.formData = this.historyData;
                this.formData.checkPass = this.historyData.password;
                //拿着列表返回的省的id去查市的接口
                // console.log("省市区:", this.cityList, this.areaList);
                // 回显省市区
                //查询省的接口
                let data5 = { parentId: this.formData.province };
                searchCity(data5).then((res)=>{
                    if (res.statusCode == "200"){
                        this.cityList = [];
                        // console.log("查询所有的市级", res.data);
                        res.data.map(v=>{
                            this.cityList.push({name: v.name, id: v.id })
                        })
                    }
                }).catch(()=>{}).then(()=> {
                    let data6 = { parentId: this.formData.city };
                    //查询市--回调接口
                    searchCity(data6).then((res)=>{
                        if (res.statusCode == "200"){
                            this.areaList = [];
                            // console.log("查询所有的区/县:", res.data);
                            res.data.map(v=>{
                                this.areaList.push({name: v.name, id: v.id })
                            })
                        }
                    })  
                })

            }
        },

        //全局方法封装
        addEdmitFun(){
            this.searchCityData(); // 查询省-市-区/县
            this.searchCsIdStatusInfo(); //查询状态正常的客服
            this.search_userType(); //查询用户类型接口
            this.search_accountType(); //查询账号类型的接口
        }
    },
    watch:{
        historyData: function (val) {
            this.formData = val;
            // console.log("watch:", val);
            this.get_title()
        },
        title: function (title) {
            // console.log("tittle:", title);
            this.title_name = title;
            this.get_title() // 判断tilte 是哪个model框
        }
    }
}
</script>

 

